package com.kehutong.payfees.util;

import org.coraframework.inject.Singleton;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.util.Objects;
import org.coraframework.util.Queue;


@Singleton
public class EventQueue extends Thread {
	
	private static final Logger logger = LoggerFactory.getLogger(EventQueue.class);
	
	private EventQueue() {
		isFlag = false;
		queue = new Queue<>();
		setDaemon(true);
		this.startUP();
	}
	
	private boolean isFlag;
	private Queue<Runnable> queue;

	
	public boolean addWork(Runnable run) {
		logger.info("queue task count={}", queue.size());
		synchronized (this) {
			queue.push(run);
			this.notify();
		}
		return true;
	}
	
	public void startUP() {
		isFlag = false;
		this.start();
	}
	
	public void shutDown() {
		isFlag = true;
	}
	
	@Override
	public void run() {
		while (!isFlag) {
			Runnable worker = null;
			try {
				worker = getWorker();
				if (Objects.nonNull(worker)) {
					worker.run();
				}
			} catch (Exception e) {
				logger.error("", e);
			}
		}
	}
	
	private Runnable getWorker() throws InterruptedException {
		Runnable worker;
		synchronized (this) {
			while ((worker = queue.pop()) == null) {
				this.wait(1000L);
			}
		}
		
		return worker;
	}


}
